<template>
  <div>
    <van-search
      :show-action="true"
      ref="input"
      placeholder="搜索订单"
      v-model="searchValue"
      @search="handleSearch()"
    >
      <p slot="action" class="text-red" @click="$router.push('/order')">取消</p>
    </van-search>
    <div class="p-10">
      <div class="fs-13 text-content flex j-between a-center">
        <span>历史搜索</span>
        <van-icon
          v-if="searchHistory"
          @click="handleDeleteSearchHistory()"
          class="fs-13 text-grey"
          name="delete"
        />
      </div>
      <div v-if="searchHistory" class="flex flex-wrap m-t-10">
        <p
          @click="handleSearch(item)"
          v-for="(item, index) in searchHistory"
          :key="index"
          class="p-h-15 fs-13 text-content p-v-5 bg-block-grey m-5 b-r-20 fw-300"
        >{{item}}</p>
      </div>
      <p v-else class="fs-12 text-grey m-t-10">暂无搜索历史</p>
    </div>
  </div>
</template>

<script>
import { getItem, setItem, removeItem } from '@/utils/storage'
export default {
  data () {
    return {
      searchValue: '',
      searchHistory: null
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    async init () {
      this.searchHistory = await this.getSearchHistory()
      await this.$refs.input.querySelector('input').focus()
    },
    handleSearch (item) {
      this.$router.push({
        path: `/order/search/result`,
        query: {
          val: item || this.searchValue
        }
      })
      this.addSearchHistory(item || this.searchValue)
    },
    handleDeleteSearchHistory () {
      this.$dialog.confirm({
        title: '提示',
        message: '是否删除搜索历史?',
        confirmButtonText: '删除',
        confirmButtonColor: '#fd4f51'
      }).then(() => {
        this.removeSearchHistory()
        this.searchHistory = null
      }).catch(() => {

      })
    },
    async removeSearchHistory () {
      await removeItem('search')
    },
    async addSearchHistory (value) {
      let item = await this.getSearchHistory()
      if (item) {
        // 已经有搜索历史
        let searchArr = item
        let hasAleadySearchIndex = searchArr.indexOf(value)
        // 搜索历史中有当前搜索过的
        if (hasAleadySearchIndex > -1) searchArr.splice(hasAleadySearchIndex, 1)
        searchArr.unshift(value)
        setItem('search', JSON.stringify(searchArr))
      } else {
        await setItem('search', JSON.stringify([value]))
      }
    },
    async getSearchHistory () {
      let searchArr = JSON.parse(await getItem('search'))
      return searchArr
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
